<?php

abstract class ViewRenderer
{
    protected $view;
    protected $request;

    public function __construct(Request $request,$view)
    {
        $this->view = $view;
        if (!file_exists($this->viewPath($this->view))) {
            throw new Exception("the view($this->view) not found!");
        }
        $this->request = $request;
    }

    protected function viewPath($view)
    {
        return ROOT . "/application/view/" . $view;
    }

    /**
     * 定义view参数
     * @param $key
     * @param $value
     * @return mixed
     */
    function assign($key, $value)
    {
        if(in_array($key,array("req","conf","param"))){
            throw new Exception("Can't set attr named of 'req'/'conf'/'param' !");
        }
        $this->request->setAttribute($key, $value);
    }

    public abstract function display();

    public static function showRenderer(Request $request, Config $conf, $ret){
        if ($ret["code"] == 200) {
            $view = $ret["view"];
            //return is ViewRenderer class, only to display
            if (is_subclass_of($view, "ViewRenderer")) {
                $view->display();
            } else if(is_array($view)){
                @header("Content-type: application/json; charset=utf-8");
                echo json_encode($view);
            } else if( is_string($view)){
                //Get the ViewRenderer from config.
                $ext = pathinfo($view, PATHINFO_EXTENSION);
                $viewRendererAry = $conf->getConfig(array("views_renderer", "controller"), NULL);
                //view renderer class mast in custom autoload,if not throw exception.
                $viewRenderer = $viewRendererAry[$ext];
                try {
                    invokeMethod($viewRenderer, array($request,$view), "display");
                } catch (Exception $e) {
                    $request->show_500($e);
                }
            }
        } else if ($ret["code"] == 404) {
            $request->show_404();
        } else {
            $request->show_500($ret["view"]);
        }
    }
}
